package server.transport;

import server.proxy.ClientHandlerInterface;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketAcceptor extends Thread {
    private ServerSocket serverSocket;
    ClientHandlerInterface clientHandler;

    public SocketAcceptor(int port, ClientHandlerInterface clientHandler) throws IOException {
        super("Socket acceptor");
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(2000);
        this.clientHandler = clientHandler;
    }

    @Override
    public void run() {
        while(!Thread.interrupted()) {
            try {
                Socket clientSocket = serverSocket.accept();
                clientHandler.onClientConnected(clientSocket);
                System.out.println("new client");
            } catch(SocketTimeoutException e) {

            } catch(IOException e) {
                System.out.println("couldn't create client");
            }
        }
    }
}
